<template>
  <div class="page-content">
    <div class="windows-management">
      <div class="page-header">
        <div class="header-left">
          <!-- 统计数字 -->
          <div class="stats-inline">
            <div class="stat-item">
              <span class="stat-value">{{ stats.total_windows }}</span>
              <span class="stat-label">总窗口</span>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <span class="stat-value">{{ stats.online_windows }}</span>
              <span class="stat-label">在线</span>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <span class="stat-value">{{ stats.offline_windows }}</span>
              <span class="stat-label">离线</span>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <span class="stat-value">{{ stats.today_diamonds }}</span>
              <span class="stat-label">今日钻石</span>
            </div>
          </div>
        </div>
        <div class="header-actions">
          <div class="view-toggle">
            <div class="toggle-buttons">
              <button 
                :class="['toggle-btn', { active: viewMode === 'list' }]"
                @click="viewMode = 'list'"
              >
                列表
              </button>
              <button 
                :class="['toggle-btn', { active: viewMode === 'grid' }]"
                @click="viewMode = 'grid'"
              >
                网格
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner">
          <div class="spinner"></div>
          <p>加载中...</p>
        </div>
      </div>

      <!-- 窗口列表/网格 -->
      <div v-else class="windows-container">
        <!-- 列表模式 -->
        <div v-if="viewMode === 'list'" class="windows-list">
          <div class="table-wrapper">
            <div class="list-header">
              <!-- 冻结列 -->
              <div class="header-cell checkbox-cell frozen-col">
                <input 
                  type="checkbox" 
                  v-model="selectAll"
                  @change="handleSelectAll"
                  :indeterminate="isIndeterminate"
                  class="custom-checkbox"
                />
              </div>
              <div class="header-cell window-id-col frozen-col">窗口ID</div>
              <!-- 可滚动列 -->
              <div class="header-cell">角色名</div>
              <div class="header-cell">游戏</div>
              <div class="header-cell">设备号</div>
              <div class="header-cell">大区</div>
              <div class="header-cell">等级</div>
              <div class="header-cell">战斗力</div>
              <div class="header-cell">金币</div>
              <div class="header-cell">钻石</div>
              <div class="header-cell">版本</div>
              <div class="header-cell">配置名称</div>
              <div class="header-cell">当前任务</div>
              <div class="header-cell">状态</div>
            </div>
            <div v-if="windowList.length === 0" class="empty-state-list">
              <div class="empty-icon">📋</div>
              <div class="empty-text">暂无窗口数据</div>
              <div class="empty-desc">等待游戏脚本端传来数据</div>
            </div>
            <div v-else v-for="role in windowList"
                 :key="role.id" 
                 class="list-row"
                 :class="{ selected: selectedRoles.includes(role.id) }">
              <!-- 冻结列 -->
              <div class="cell checkbox-cell frozen-col">
                <input 
                  type="checkbox"
                  :checked="selectedRoles.includes(role.id)"
                  @change="toggleRoleSelection(role.id)"
                  class="custom-checkbox"
                />
              </div>
              <div class="cell window-id-col frozen-col">{{ role.window_id }}</div>
              <!-- 可滚动列 -->
              <div class="cell">{{ role.name || '-' }}</div>
              <div class="cell">{{ role.game }}</div>
              <div class="cell">{{ role.device_id }}</div>
              <div class="cell">{{ role.region || '-' }}</div>
              <div class="cell">{{ role.level || '-' }}</div>
              <div class="cell">{{ formatCombatPower(role.combat_power) }}</div>
              <div class="cell">{{ getDataValue(role.datas, 'gold') }}</div>
              <div class="cell">{{ getDataValue(role.datas, 'diamond') }}</div>
              <div class="cell">{{ role.version || '-' }}</div>
              <div class="cell">{{ role.config_name || '未配置' }}</div>
              <div class="cell">{{ role.cur_task || '无任务' }}</div>
              <div class="cell">
                <span :class="['status', getStatus(role)]">
                  {{ getStatusText(role) }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 网格模式 -->
        <div v-else class="windows-grid">
          <div v-if="windowList.length === 0" class="empty-state-grid">
            <div class="empty-icon">🖼️</div>
            <div class="empty-text">暂无窗口数据</div>
            <div class="empty-desc">等待窗口连接或数据加载</div>
          </div>
          <div v-else v-for="role in windowList" :key="role.id" class="window-card">
            <div class="card-header">
              <div class="card-checkbox">
                <input 
                  type="checkbox"
                  :checked="selectedRoles.includes(role.id)"
                  @change="toggleRoleSelection(role.id)"
                  class="custom-checkbox"
                />
              </div>
              <div class="card-status" :class="getStatus(role)">
                {{ getStatusText(role) }}
              </div>
            </div>
            <div class="card-content">
              <div class="role-info">
                <h3 class="role-name">{{ role.name || '未知角色' }}</h3>
                <p class="window-id">窗口 #{{ role.window_id }}</p>
              </div>
              <div class="role-details">
                <div class="detail-item">
                  <span class="label">游戏:</span>
                  <span class="value">{{ role.game }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">等级:</span>
                  <span class="value">{{ role.level || '-' }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">战斗力:</span>
                  <span class="value">{{ formatCombatPower(role.combat_power) }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">配置:</span>
                  <span class="value">{{ role.config_name || '未配置' }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserRoles, getRoleStats } from '../api/roles'

export default {
  name: 'WindowSettings',
  setup() {
    const loading = ref(false)
    const viewMode = ref('list')

    // 统计数据
    const stats = ref({
      total_windows: 0,
      online_windows: 0,
      offline_windows: 0,
      total_diamonds: 0,
      today_diamonds: 0
    })

    // 窗口列表数据
    const windowList = ref([])
    const selectedRoles = ref([])
    const selectAll = ref(false)
    const isIndeterminate = ref(false)

    // 加载数据
    const loadData = async () => {
      loading.value = true
      try {
        // 并行加载统计信息和角色列表
        const [statsResponse, rolesResponse] = await Promise.all([
          getRoleStats(),
          getUserRoles()
        ])

        stats.value = statsResponse.data || stats.value
        windowList.value = rolesResponse.data || []
        
        // 使用nextTick确保数据更新后再更新选择状态
        await nextTick()
        updateSelectState()
      } catch (error) {
        console.error('加载数据失败:', error)
        let errorMessage = '加载数据失败'
        
        if (error.response?.status === 401) {
          errorMessage = '登录已过期，请重新登录'
          setTimeout(() => {
            window.location.href = '/login'
          }, 1500)
        } else if (error.response?.data?.error || error.response?.data?.message) {
          errorMessage = error.response.data.error || error.response.data.message
        }
        
        ElMessage.error(errorMessage)
      } finally {
        loading.value = false
      }
    }

    // 更新选择状态
    const updateSelectState = () => {
      try {
        const selectedCount = selectedRoles.value ? selectedRoles.value.length : 0
        const totalCount = windowList.value ? windowList.value.length : 0
        selectAll.value = selectedCount === totalCount && totalCount > 0
        isIndeterminate.value = selectedCount > 0 && selectedCount < totalCount
      } catch (error) {
        console.error('更新选择状态失败:', error)
        selectAll.value = false
        isIndeterminate.value = false
      }
    }

    // 切换角色选择
    const toggleRoleSelection = (roleId) => {
      const index = selectedRoles.value.indexOf(roleId)
      if (index > -1) {
        selectedRoles.value.splice(index, 1)
      } else {
        selectedRoles.value.push(roleId)
      }
      updateSelectState()
    }

    // 全选功能
    const handleSelectAll = (event) => {
      const checked = event.target.checked
      if (checked) {
        selectedRoles.value = windowList.value.map(role => role.id)
      } else {
        selectedRoles.value = []
      }
      updateSelectState()
    }

    // 获取角色状态
    const getStatus = (role) => {
      if (role.websocket && role.websocket.trim() !== '') {
        return 'online'
      }
      return 'offline'
    }

    const getStatusText = (role) => {
      const status = getStatus(role)
      const statusMap = {
        'online': '在线',
        'offline': '离线'
      }
      return statusMap[status] || '未知'
    }

    // 格式化战斗力
    const formatCombatPower = (power) => {
      if (!power) return '-'
      return power.toLocaleString()
    }

    const getDataValue = (datas, key) => {
      if (datas && datas[key] !== undefined && datas[key] !== null) {
        return datas[key]
      }
      return '-'
    }

    onMounted(async () => {
      await loadData()
    })

    return {
      loading,
      viewMode,
      stats,
      windowList,
      selectedRoles,
      selectAll,
      isIndeterminate,
      loadData,
      updateSelectState,
      toggleRoleSelection,
      handleSelectAll,
      getStatus,
      getStatusText,
      formatCombatPower,
      getDataValue
    }
  }
}
</script>

<style scoped>
.page-content {
  padding: 0;
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.windows-management {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;
  padding: 0 4px;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.page-header h2 {
  margin: 0;
  color: #1d1d1f;
  font-size: 32px;
  font-weight: 700;
  letter-spacing: -0.5px;
}

/* 内联统计数字 */
.stats-inline {
  display: flex;
  align-items: center;
  gap: 24px;
}

.stat-item {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #1d1d1f;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #86868b;
  font-weight: 400;
}

.stat-divider {
  width: 1px;
  height: 20px;
  background: rgba(0, 0, 0, 0.1);
}

.header-actions {
  display: flex;
  align-items: center;
  margin-top: 8px;
}

.view-toggle {
  display: flex;
  align-items: center;
}

.toggle-buttons {
  display: flex;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  padding: 2px;
}

.toggle-btn {
  background: none;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #86868b;
  cursor: pointer;
  transition: all 0.2s ease;
}

.toggle-btn.active {
  background: white;
  color: #1d1d1f;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.toggle-btn:hover:not(.active) {
  color: #1d1d1f;
}

/* 加载状态 */
.loading-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-top: 3px solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-spinner p {
  margin: 0;
  color: #86868b;
  font-size: 16px;
}

/* 窗口容器 */
.windows-container {
  flex: 1;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.05);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 自定义复选框 */
.custom-checkbox {
  width: 18px;
  height: 18px;
  border: 2px solid #d1d5db;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  position: relative;
  appearance: none;
  transition: all 0.2s ease;
}

.custom-checkbox:checked {
  background: #007aff;
  border-color: #007aff;
}

.custom-checkbox:checked::after {
  content: '✓';
  position: absolute;
  top: -2px;
  left: 2px;
  color: white;
  font-size: 12px;
  font-weight: bold;
}

/* 列表模式样式 */
.windows-list {
  flex: 1;
  overflow: hidden;
}

.table-wrapper {
  height: 100%;
  overflow: auto;
  position: relative;
}

.list-header {
  display: grid;
  grid-template-columns: 50px 80px 120px 100px 140px 100px 80px 100px 80px 80px 80px 120px minmax(140px, 2fr) minmax(80px, 1fr);
  background: #f8f9fa;
  padding: 16px 20px;
  font-weight: 600;
  color: #1d1d1f;
  font-size: 14px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  gap: 8px;
  min-width: 1200px;
  position: sticky;
  top: 0;
  z-index: 10;
}

.list-row {
  display: grid;
  grid-template-columns: 50px 80px 120px 100px 140px 100px 80px 100px 80px 80px 80px 120px minmax(140px, 2fr) minmax(80px, 1fr);
  padding: 16px 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  align-items: center;
  transition: all 0.2s ease;
  gap: 8px;
  min-width: 1200px;
}

.list-row:hover {
  background: rgba(0, 0, 0, 0.02);
}

.list-row.selected {
  background: rgba(0, 122, 255, 0.05);
}

.header-cell, .cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.cell {
  color: #1d1d1f;
}

/* 冻结列样式 */
.frozen-col {
  position: sticky;
  background: inherit;
  z-index: 5;
}

.checkbox-cell.frozen-col {
  left: 0;
}

.window-id-col.frozen-col {
  left: 58px;
}

/* 网格模式样式 */
.windows-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
  padding: 20px;
  overflow: auto;
}

.window-card {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.2s ease;
}

.window-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: rgba(0, 0, 0, 0.02);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.card-status {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.card-status.online {
  background: rgba(52, 199, 89, 0.1);
  color: #34c759;
}

.card-status.offline {
  background: rgba(255, 59, 48, 0.1);
  color: #ff3b30;
}

.card-content {
  padding: 16px;
}

.role-name {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1d1d1f;
}

.window-id {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: #86868b;
}

.role-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-item .label {
  font-size: 14px;
  color: #86868b;
}

.detail-item .value {
  font-size: 14px;
  color: #1d1d1f;
  font-weight: 500;
}

.status {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status.online {
  background: rgba(52, 199, 89, 0.1);
  color: #34c759;
}

.status.offline {
  background: rgba(255, 59, 48, 0.1);
  color: #ff3b30;
}

/* 空状态样式 */
.empty-state-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  color: #86868b;
  grid-column: 1 / -1;
}

.empty-state-grid {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120px 20px;
  color: #86868b;
  grid-column: 1 / -1;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 16px;
  font-weight: 500;
  color: #1d1d1f;
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
  color: #86868b;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    margin-top: 0;
  }
}

@media (max-width: 768px) {
  .stats-inline {
    flex-wrap: wrap;
    gap: 16px;
  }
  
  .stat-divider {
    display: none;
  }
  
  .page-header h2 {
    font-size: 28px;
  }
  
  .stat-value {
    font-size: 20px;
  }
  
  .windows-grid {
    grid-template-columns: 1fr;
    padding: 16px;
  }
}

@media (max-width: 640px) {
  .stats-inline {
    grid-template-columns: repeat(2, 1fr);
    display: grid;
    gap: 12px;
  }
  
  .stat-item {
    flex-direction: column;
    gap: 4px;
    text-align: center;
  }
}
</style>
